package com.orange.notificationsummary;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.orange.homescreen.pil.NotificationSummaryInterface;
import com.orange.homescreen.pil.PILCore;
import com.orange.homescreen.pil.PILInterfaceManager;
import com.orange.homescreen.pil.base.BasePILMonitor;
import com.orange.homescreen.pil.base.PILListener;
import com.orange.notificationsummary.event.pil.defaultimpl.BaseEvent;
import com.orange.notificationsummary.loader.LoaderController;
import com.orange.notificationsummary.utils.Constants;
import com.orange.notificationsummary.utils.LogHelper;
import com.orange.notificationsummary.utils.MissedCallUtils;

public class SummaryActivity extends Activity implements OnClickListener {
	private static final String					TAG						= "SummaryActivity";

	private static final int					ALL_UPDATE				= -1;
	private static final int					CONTACT_UPDATE			= 0;
	private static final int					MISSCALL_UPDATE			= 1;
	private static final int					UNMSG_UPDATE			= 2;
	private static final int					VVM_UPDATE				= 3;

	private static NotificationSummaryInterface	sNotificationInterfc;

	private volatile static BasePILMonitor		sContactMonitor;
	private volatile static BasePILMonitor		sMissedCallMonitor;
	private volatile static BasePILMonitor		sUnreadMsgMonitor;
	private volatile static BroadcastReceiver	sVoiceMailReceiver1;
	// comment by gaoge 2011-09-15,because voiceMailReceiver2 is no use if we
	// already have voiceMailReceiver1
	// private volatile static BroadcastReceiver voiceMailReceiver2;

	private PILListener							mContactListener		= new NotificationPILListener(
																				CONTACT_UPDATE);
	private PILListener							mMissedCallListener		= new NotificationPILListener(
																				MISSCALL_UPDATE);
	private PILListener							mMsgListener			= new NotificationPILListener(
																				UNMSG_UPDATE);
	private PILListener							mVVMListener			= new NotificationPILListener(
																				VVM_UPDATE);

	private List<EventTypeAndCount>				mEventTypeAndCount;
	private List<BaseEvent>						mEvents;
	private List<BaseEvent>						mMissCallsEvents		= null;
	private List<BaseEvent>						mUnreadMsgEvents		= null;
	private List<BaseEvent>						mUnreadVoicemailEvents	= null;

	private AsyncTask<String, Void, Boolean>	mClearAsyncTask;

	private LinearLayout						mEvent_panels;

	private ListView							mEvents_list;
	private SummaryListAdapter					mSummaryListAdapter;

	private Button								mClearAll;
	private Button								mDone;
	private ImageView							mBottomLine;

	boolean										mShowMessage			= true;
	boolean										mShowMisscall			= true;
	boolean										mShowVoicemail			= true;

	private EventTypeAndCount					mMisscallEvent			= null;
	private EventTypeAndCount					mMessageEvent			= null;
	private EventTypeAndCount					mVoicemailEvent			= null;

	LoaderController							mLoaderController		= null;

	private MenuItem							mClearMenuItem			= null;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.summary_main);

		init();
		registerObserver();
	}

	@Override
	protected void onResume() {
		if (setShowFlag()) {
			LogHelper
					.d(TAG,
							"################################ 1111111111111111111111 updateInfo");
			updateInfo(ALL_UPDATE);
		} else {
			showNoEventView();
		}
		judgeWhertherToShowClearAllButton();
		super.onResume();
	}

	protected void onPause() {
		mLoaderController.abortLoaders();
		mLoaderController.reset();
		super.onPause();
	}

	private void init() {

		if (!PILCore.isInialized()) {
			PILCore.initialize(this);
		}

		mEventTypeAndCount = new ArrayList<EventTypeAndCount>();
		mEvents = new ArrayList<BaseEvent>();

		mEvent_panels = (LinearLayout) findViewById(R.id.event_panels);
		mEvent_panels.removeAllViews();
		mEvents_list = (ListView) findViewById(R.id.events_list);
		mSummaryListAdapter = new SummaryListAdapter(this,
				new ArrayList<BaseEvent>());
		mEvents_list.setAdapter(mSummaryListAdapter);

		mClearAll = (Button) findViewById(R.id.clear);
		mClearAll.setOnClickListener(this);
		mDone = (Button) findViewById(R.id.done);
		mDone.setOnClickListener(this);
		mBottomLine = (ImageView) findViewById(R.id.bottom_lines);

		mEvents_list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				mEvents.get(arg2).lookDetail();
			}

		});
		// if (!PILCore.isInialized()) {
		// PILCore.initialize(this);
		// }

		mLoaderController = new LoaderController();
	}

	private boolean setShowFlag() {
		SharedPreferences aSharedPreferences = getSharedPreferences(
				NotificationGlobal.NOTIFICATION_SETTING, 0);
		mShowMisscall = aSharedPreferences.getBoolean("0", true);
		mShowVoicemail = aSharedPreferences.getBoolean("1", true);
		mShowMessage = aSharedPreferences.getBoolean("2", true);
		// if (!showMisscall && !showVoicemail && !showMessage) {
		// return false;
		// } else {
		// return true;
		// }

		return mShowMisscall || mShowVoicemail || mShowMessage;
	}

	private void bindNewEvents(int flag) {
		LogHelper
				.d(TAG,
						"$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ bindNewEvents,flag : "
								+ flag);
		switch (flag) {
		case MISSCALL_UPDATE:
			if (mShowMisscall) {
				mLoaderController.startMissCallLoader(this);
			}
			break;
		case UNMSG_UPDATE:
			if (mShowMessage) {
				mLoaderController.startUnreadMsgLoader(this);
			}
			break;
		case VVM_UPDATE:
			if (mShowVoicemail) {
				mLoaderController.startVoiceMailLoader(this);
			}
			break;
		default:
			// misscall
			if (mShowMisscall) {
				mLoaderController.startMissCallLoader(this);
			}
			// unreadMessage
			if (mShowMessage) {
				mLoaderController.startUnreadMsgLoader(this);
			}
			if (mShowVoicemail) {
				mLoaderController.startVoiceMailLoader(this);
			}
		}
	}

	@Override
	public void onClick(View arg0) {
		if (arg0.getId() == R.id.clear) {
			LogHelper.d(TAG,
					"######################## onClick() clearAllEventSelect ");
			clearAllEventSelect();
			judgeWhertherToShowClearAllButton();
		} else if (arg0.getId() == R.id.done) {
			closeActivity();
		} else {
		}
	}

	@Override
	public void finish() {
		stopMonitor();
		mLoaderController.abortLoaders();
		mLoaderController.reset();
		super.finish();
	}

	private void closeActivity() {
		// stopMonitor();
		SummaryActivity.this.finish();
	}

	private void startSettingActivity() {
		Intent intent = new Intent();
		intent.setAction("com.orange.lockscreen.action.EVENT_SETTING");
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
	}

	public void setEventData(List<BaseEvent> eventList,
			EventTypeAndCount newEvent, int loaderType) {
		// dialog.show();
		switch (loaderType) {
		case LoaderController.MISSCALL_LOADER:
			this.mMissCallsEvents = eventList;
			mMisscallEvent = newEvent;
			break;
		case LoaderController.UNREADMSG_LOADER:
			this.mUnreadMsgEvents = eventList;
			mMessageEvent = newEvent;
			break;
		case LoaderController.VOICEMAIL_LOADER:
			this.mUnreadVoicemailEvents = eventList;
			mVoicemailEvent = newEvent;
			break;
		default:
			break;

		}

		LogHelper.d(TAG, "setEventData. loaderType: " + loaderType);
		dealEventIndicator();
		refreshIndicator();
		sortAllEvent();
		refreshEventAreaViewer();

		// dialog.dismiss();
	}

	private void dealEventIndicator() {

		if (mEventTypeAndCount != null) {
			mEventTypeAndCount.clear();
		}
		if (mMessageEvent != null && mMessageEvent.event_count != 0
				&& mShowMessage) {
			mEventTypeAndCount.add(mMessageEvent);
		}

		if (mMisscallEvent != null && mMisscallEvent.event_count != 0
				&& mShowMisscall) {
			mEventTypeAndCount.add(mMisscallEvent);
		}

		if (mVoicemailEvent != null && mVoicemailEvent.event_count != 0
				&& mShowVoicemail) {
			mEventTypeAndCount.add(mVoicemailEvent);
		}
		if (mEventTypeAndCount != null) {
			try {
				Collections.sort(mEventTypeAndCount);
			} catch (Exception ex) {
				LogHelper.e(TAG, "dealEventIndicator. ", ex);
			}
		}
	}

	private void refreshIndicator() {
		mEvent_panels.removeAllViews();
		if (mEventTypeAndCount != null && !mEventTypeAndCount.isEmpty()) {
			for (EventTypeAndCount e : mEventTypeAndCount) {
				mEvent_panels.addView(e.getEventView());
			}
			findViewById(R.id.no_new_evnet).setVisibility(View.GONE);
			findViewById(R.id.clear).setEnabled(true);
			findViewById(R.id.clear).setFocusable(true);
			if (mClearMenuItem != null) {
				mClearMenuItem.setEnabled(true);
			}
		} else {
			findViewById(R.id.no_new_evnet).setVisibility(View.VISIBLE);
			findViewById(R.id.clear).setEnabled(false);
			findViewById(R.id.clear).setFocusable(false);
			if (mClearMenuItem != null) {
				mClearMenuItem.setEnabled(false);
			}
		}
	}

	private void sortAllEvent() {
		if (mEvents != null) {
			mEvents.clear();
		}
		if (mMissCallsEvents != null && mShowMisscall
				&& !mMissCallsEvents.isEmpty()) {
			LogHelper.v(TAG,
					"sortAllEvent. misscall: " + mMissCallsEvents.size());
			mEvents.addAll(mMissCallsEvents);
		}

		if (mUnreadMsgEvents != null && mShowMessage
				&& !mUnreadMsgEvents.isEmpty()) {
			LogHelper.v(TAG, "sortAllEvent. msg: " + mUnreadMsgEvents.size());
			mEvents.addAll(mUnreadMsgEvents);
		}

		if (mUnreadVoicemailEvents != null && mShowVoicemail
				&& !mUnreadVoicemailEvents.isEmpty()) {
			LogHelper.v(TAG,
					"sortAllEvent. vvm: " + mUnreadVoicemailEvents.size());
			mEvents.addAll(mUnreadVoicemailEvents);
		}

		if (mEvents != null)
			Collections.sort(mEvents);
	}

	private void refreshEventAreaViewer() {
		mSummaryListAdapter.mEvents = mEvents;
		if (mEvents != null) {
			LogHelper.i(TAG,
					"refreshEventAreaViewer. events: " + mEvents.size());
		}
		mSummaryListAdapter.notifyDataSetChanged();
		judgeWhertherToShowClearAllButton();
	}

	private class ClearAsyncTask extends AsyncTask<String, Void, Boolean> {

		@Override
		protected Boolean doInBackground(String... params) {
			try {
				clearAllEvent();
				LogHelper
						.d(TAG,
								"#################### ClearAsyncTask doInBackground() invoke clearAllEvent()");
			} catch (Exception ex) {
				LogHelper.e(TAG, "doInBackground. clear event error:", ex);
			}
			return Boolean.TRUE;
		}

		// add by gaoge 2011-09-15
		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

			mEvent_panels.removeAllViews();

			mEvents.clear();
			cleanAllEvents();

			mSummaryListAdapter.mEvents.clear();
			LogHelper.i(TAG, "clearAllEventSelect. events: " + mEvents.size()
					+ " ,mSummaryListAdapter.events: "
					+ mSummaryListAdapter.mEvents.size());
			mSummaryListAdapter.notifyDataSetChanged();
			judgeWhertherToShowClearAllButton();

			findViewById(R.id.no_new_evnet).setVisibility(View.VISIBLE);
			findViewById(R.id.clear).setEnabled(false);
			findViewById(R.id.clear).setFocusable(false);

			if (mClearMenuItem != null) {
				mClearMenuItem.setEnabled(false);
			}
			NotificationGlobal.clearSelect(SummaryActivity.this);
		}

	}

	private void cleanAllEvents() {

		if (null != mUnreadVoicemailEvents) {
			mUnreadVoicemailEvents.clear();
			LogHelper.d(TAG,
					" [cccccccccccccccccccccccccc]   mUnreadVoicemailEvents.size(): "
							+ mUnreadVoicemailEvents.size());
		}
		if (null != mUnreadMsgEvents) {
			mUnreadMsgEvents.clear();
			LogHelper.d(TAG,
					"[cccccccccccccccccccccccccc] mUnreadMsgEvents.size(): "
							+ mUnreadMsgEvents.size());
		}
		if (null != mMissCallsEvents) {
			mMissCallsEvents.clear();
			LogHelper.d(TAG,
					"[cccccccccccccccccccccccccc] mMissCallsEvents.size(): "
							+ mMissCallsEvents.size());
		}

	}

	private void clearAllEvent() {
		NotificationSummaryInterface mInterface = (NotificationSummaryInterface) PILInterfaceManager
				.getInterface(NotificationSummaryInterface.class);

		if (this.mMissCallsEvents != null && !mMissCallsEvents.isEmpty()) {
			String[] ids = new String[mMissCallsEvents.size()];
			for (int i = 0; i < ids.length; i++) {
				ids[i] = String.valueOf(mMissCallsEvents.get(i).id);
			}
			boolean upSuccess = mInterface.updateCallLogStatusByIds(this, ids);
			if (upSuccess) {
				MissedCallUtils.cancelMissedCallsNotification(this);
			}
		}

		if (this.mUnreadMsgEvents != null && !mUnreadMsgEvents.isEmpty()) {
			String[] threadIds = new String[mUnreadMsgEvents.size()];
			for (int i = 0; i < threadIds.length; i++) {
				threadIds[i] = String.valueOf(mUnreadMsgEvents.get(i).threadId);
			}
			mInterface.updateUnreadMsgStatusByThreadIds(this, threadIds);
		}

		if (this.mUnreadVoicemailEvents != null
				&& !mUnreadVoicemailEvents.isEmpty()) {
			String[] ids = new String[mUnreadVoicemailEvents.size()];
			for (int i = 0; i < ids.length; i++) {
				ids[i] = String.valueOf(mUnreadVoicemailEvents.get(i).id);
			}
			mInterface.updateVVMStatusByIds(this, ids);
		}

	}

	/**
	 * register observer
	 */
	private void registerObserver() {
		if (sNotificationInterfc == null) {
			sNotificationInterfc = (NotificationSummaryInterface) PILInterfaceManager
					.getInterface(NotificationSummaryInterface.class);
		}

		sContactMonitor = sNotificationInterfc.getContactsMonitor(this);
		if (sContactMonitor != null) {
			sContactMonitor.addListener(mContactListener);
		}
		sMissedCallMonitor = sNotificationInterfc.getMissedCallMonitor(this);
		if (sMissedCallMonitor != null) {
			sMissedCallMonitor.addListener(mMissedCallListener);
		}
		sUnreadMsgMonitor = sNotificationInterfc.getUnreadMsgMonitor(this);
		if (sUnreadMsgMonitor != null) {
			sUnreadMsgMonitor.addListener(mMsgListener);
		}

		sVoiceMailReceiver1 = new VoiceMailReceiver();

		IntentFilter appChangedFilter = new IntentFilter();
		appChangedFilter.addAction(Constants.ACTION_VOICE_MAIL);
		appChangedFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
		appChangedFilter.addAction(Intent.ACTION_PACKAGE_INSTALL);
		appChangedFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
		appChangedFilter.addDataScheme("package");

		registerReceiver(sVoiceMailReceiver1, appChangedFilter);

		// voiceMailReceiver2 = new VoiceMailReceiver();
		//
		// IntentFilter voiceMailUpdateFilter = new IntentFilter();
		// voiceMailUpdateFilter.addAction(Constants.ACTION_VOICE_MAIL);
		//
		// registerReceiver(voiceMailReceiver2, voiceMailUpdateFilter);
	}

	/**
	 * unregister observer
	 */
	private void stopMonitor() {
		try {
			unregisterReceiver(sVoiceMailReceiver1);
			// unregisterReceiver(voiceMailReceiver2);
		} catch (IllegalArgumentException e) {
			LogHelper.e(TAG, "stopMonitor. ", e);
		}
	}

	private synchronized void updateInfo(int flag) {
		bindNewEvents(flag);
		judgeWhertherToShowClearAllButton();
	}

	private void clearAllEventSelect() {
		LogHelper.d(TAG, "################### clearAllEventSelect() ");
		if (mClearAsyncTask != null) {
			Status tempStatus = mClearAsyncTask.getStatus();
			if (tempStatus != AsyncTask.Status.RUNNING
					|| tempStatus != AsyncTask.Status.FINISHED) {
				mClearAsyncTask.cancel(true);
			}
		}
		mClearAsyncTask = new ClearAsyncTask();
		mClearAsyncTask.execute();
		// event_panels.removeAllViews();
		//
		// events.clear();
		// mSummaryListAdapter.events.clear();
		// LogHelper.i(TAG,
		// "clearAllEventSelect. events: " + events.size()
		// + " ,mSummaryListAdapter.events: "
		// + mSummaryListAdapter.events.size());
		// mSummaryListAdapter.notifyDataSetChanged();
		// judgeWhertherToShowClearAllButton();
		//
		// findViewById(R.id.no_new_evnet).setVisibility(View.VISIBLE);
		// findViewById(R.id.clear).setEnabled(false);
		// findViewById(R.id.clear).setFocusable(false);
		//
		// if (mClearMenuItem != null) {
		// mClearMenuItem.setEnabled(false);
		// }
		// NotificationGlobal.clearSelect(this);
	}

	private void showNoEventView() {
		findViewById(R.id.no_new_evnet).setVisibility(View.VISIBLE);
		findViewById(R.id.clear).setEnabled(false);
		findViewById(R.id.clear).setFocusable(false);
		if (mClearMenuItem != null) {
			mClearMenuItem.setEnabled(false);
		}
		mSummaryListAdapter.mEvents = null;
		mSummaryListAdapter.notifyDataSetChanged();
		judgeWhertherToShowClearAllButton();
		mEvent_panels.removeAllViews();
	}

	class VoiceMailReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			Uri uri = intent.getData();
			String p = " ";
			boolean updateFlag = false;
			if (uri != null) {
				p = uri.toString();
			}
			if (!TextUtils.isEmpty(action)
					&& Constants.ACTION_VOICE_MAIL.equals(action)) {
				updateFlag = true;
			}
			if (!TextUtils.isEmpty(action)
					&& p.indexOf(Constants.PKG_VOICEMAIL) != -1) {
				updateFlag = true;
			}
			LogHelper
					.d(TAG,
							"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ VoiceMailReceiver invoke NotificationPILListener's update()");
			if (updateFlag && mVVMListener != null) {
				mVVMListener.update(null);
			}
		}
	}

	class NotificationPILListener implements PILListener {
		private int	type	= -1;

		public NotificationPILListener(int type) {
			this.type = type;
		}

		public void update(Object data) {
			LogHelper
					.d(TAG,
							"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 222222222222222222222 updateInfo NotificationPILListener update invoke updateInfo(which will invoke bindNewEvents ");
			updateInfo(this.type);
		}
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		if (item.getItemId() == R.id.summary_settings) {
			startSettingActivity();
		} else if (item.getItemId() == R.id.summary_clear) {
			clearAllEventSelect();
		} else if (item.getItemId() == R.id.summary_close) {
			closeActivity();
		} else {
		}
		
		return false;
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.norificationsummary_menu, menu);

		mClearMenuItem = (MenuItem) menu.findItem(R.id.summary_clear);
		return true;
	}

	// add by gaoge 2011-07-27,for fix bug 0012964
	private void judgeWhertherToShowClearAllButton() {
		if (0 == mSummaryListAdapter.getCount()) {
			mClearAll.setVisibility(View.GONE);
			mBottomLine.setVisibility(View.GONE);
		} else {
			mClearAll.setVisibility(View.VISIBLE);
			mBottomLine.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		mClearMenuItem = (MenuItem) menu.findItem(R.id.summary_clear);
		if (0 == mSummaryListAdapter.getCount()) {
			mClearMenuItem.setVisible(false);
		} else {
			mClearMenuItem.setVisible(true);
		}
		// TODO Auto-generated method stub
		return super.onPrepareOptionsMenu(menu);
	}

}